var result_div = null;
var nest = new Nest(100);
var sessions = new Array();

Session = function(callback) { // extends Food
	this.id = new Date().getTime();
	this.type = 'none'; // time or floor or none
	this.from = 0;
	this.to = 0;
	this.thread = new Thread();
	this.pending = []; // array of url
	this.failed = []; // array of url fails
	this.results = []; // array of UserPostStat
	this.stop = false;
	this.posted = false;
	this.current_url = null;
	this.callback = callback;
}

Session.prototype.clone = function(obj) {
	if (obj != null) {
		this.id = obj.id;
		this.type = obj.type;
		this.from = obj.from;
		this.to = obj.to;
		if (obj.thread != null)
		this.thread = obj.thread;
		this.thread.pages = new Array(); // save spaces
		this.pending = new Array();
		if (obj.pending != null && obj.pending.length > 0)
			this.pending.push(obj.pending[obj.pending.length - 1]);
		this.failed = obj.failed; 
		this.results = obj.results;
		this.stop = false;
		this.posted = obj.posted;
		this.current_url = obj.current_url;
	}
}

Session.prototype.bitten = function() {
	if (this.pending.length > 0) {
		this.current_url = this.pending.shift();
		log(this.current_url);
		return this.current_url;
	}
	return null;
}

Session.prototype.hasMore = function() {
	return this.pending.length > 0 && !this.stop ;
}

Session.prototype.isFinished = function() {
	return this.stop;
}

Session.prototype.digest = function(url, has_error, content) {
	if (has_error) {
		this.failed.push(url);
		this.callback(this);
//		if (this.thread != null)
//			dao.saveThread(this.thread);
//		display_result(this);
		return;
	}
	var url_prefix = dao.getUrlPrefix();
	if (url_prefix == null || url_prefix == '') {
		alert("Please specify URL prefix in OPTION page.");
		return;
	}
	sis_set_content(url_prefix, content);
	if (this.thread.url == '') {
		this.thread.url = url;
	}
	if (this.thread.title == '') {
		var title = sis_get_title();
		this.thread.title = title;
	}
	var next_url = sis_get_next_page_url();
	if (next_url != null) {
		this.pending.push(next_url);
	}
	var page = new Page();
	page.url = url;
	page.number = sis_get_page_number();
	sis_get_posts(page);
	this.thread.pages.push(page);
	add_stat(this, page)
}

Session.prototype.takeback = function(url) {
	this.pending.push(url);
}

Session.prototype.finish = function() { 
	this.stop = true;
	this.callback(this);
}

function session_finished(session) {
	try {
		dao.saveSession(session); 
	} catch(err) {
		error(err.description);
	}
	display_result(session); 
	log("finished"); 
	
	var auto_continue = true;
	var btn = document.getElementById("btn_start"); 
	if (btn.onclick == run_stat) auto_continue = false;
	if (session.thread == null) auto_continue = false;
	if (session.current_url == null) auto_continue = false;
	if (session.thread.url == session.current_url) auto_continue = false;
	if (session.results == null || session.results.length == 0) auto_continue = false;
	if (auto_continue == false) {
		btn.value = 'Start';
		btn.onclick = run_stat; 
	} else {
		var new_session = create_new_session(session);
		start(new_session, true);
	}
}

function create_new_session(session) {
	var new_session = new Session(session.callback);
	new_session.type = session.type;
	new_session.from = session.to;
	new_session.to = new_session.from + session.to - session.from;
	if (new_session.to >= new Date().getTime()) {
		return;
	}
	var url = session.current_url;
	new_session.pending.push(url);
	new_session.thread.url = url;
	return new_session;
}

function run_stat() {
	var session = get_selected_session();
	var url = document.getElementById("url").value;
	if (session == null) {
		session = new Session(session_finished);
	} 
	if (session.pending.length == 0 || session.thread.url == null) {
		if (url == "") {
			alert("Please enter valid url");
			return;
		}
		if (session.pending.length == 0)
		session.pending.push(url);
		if (session.thread.url == null)
		session.thread.url = url;
	}
	
	var from_time = document.getElementById("from_time").value;
	var to_time = document.getElementById("to_time").value;
	var from_floor = document.getElementById("from_floor").value;
	var to_floor = document.getElementById("to_floor").value;
	if ((from_time != "" && to_time == "") || (from_time == "" && to_time != "")) {
		alert('Please set full condition');
		return;
	} else if (from_time != "" && to_time != "") {
		session.type = 'time';
		session.from = Date.parse(from_time);
		session.to = Date.parse(to_time);
	} else if ((from_floor != "" && to_floor == "") || (from_floor == "" && to_floor != "")) {
		alert('Please set full condition');
		return;
	} else if (from_floor != "" && to_floor != "") {
		session.type = 'floor';
		session.from = parseInt(from_floor, 10);
		session.to = parseInt(to_floor, 10);
	} else {
		session.type = 'none';
	}
	var btn = document.getElementById("btn_start");
	btn.value = 'Stop';
	btn.onclick = stop_stat;
	start(session, true);
}

function stop_stat() {
	var btn = document.getElementById("btn_start");
	btn.value = 'Start';
	btn.onclick = run_stat;
	nest.stop();
}

function start(session, auto_run, delay) {
	if (auto_run == undefined) auto_run = true;
	if (delay == undefined) {
		delay = parseInt(document.getElementById("session_delay").value, 10);
	}
	clear_log();
	session.stop = false;
	nest.addFood(session, auto_run, delay);
}

function add_stat(session, page) {
	// stat {
	// 	next_page: url of next page
	//  posts: table of posts
	// 		id: user id
	// 		time: posting time
	// 		floor: floor number
	
	var cnt = 0;
	for (var i in page.posts) {
		var post = page.posts[i];
		if (session.type == 'none' || 
			(session.type == 'time' && post.time >= session.from) ||
			(session.type == 'floor' && post.floor >= session.from)) {
			if (session.type == 'none' ||
				(session.type == 'time' && post.time < session.to) ||
				(session.type == 'floor' && post.floor <= session.to)) {
				var u = read_ups(session.results, post.uid);
				if (u == null) {
					u = new UserPostStat();
					u.id = post.id;
					u.uid = post.uid;
					u.count = 1;
					u.last_floor = post.floor;
					if (session.detail) {
						u.posts = new Array();
						u.posts.push(post);
					}
					session.results.push(u);
				} else {
					u.count++;
					if (session.detail) {
						u.posts.push(post);
					}
					u.last_floor = post.floor;
				}
				cnt++;
			} else {
				session.stop = true;
				break;
			}
		}
	}
	log(cnt);
}

function read_ups(array, uid) {
	for (var i in array) {
		if (array[i].uid == uid) {
			return array[i];
		}
	}
	return null;
}

function load_sessions() {
	sessions = dao.loadSessions(session_finished);
	var select = document.getElementById("sessions");
	select.options = [];
	for (var i in sessions) {
		var session = sessions[i];
		var opt = document.createElement("option");
		opt.id = session.id;
		if (session.type == 'time') {
			var df = new Date(session.from);
			var dt = new Date(session.to);
			if (session.thread.title == '') {
				opt.text = display_date(df) + "-" + display_date(dt);
			} else {
			opt.text = display_date(df) + " - " + display_date(dt) + " on " + session.thread.title;
			}
		} else {	
			if (session.thread.title == '') {
				opt.text = 'Floor: ' + session.from + " - " + session.to;
			} else {
			opt.text = 'Floor: ' + session.from + " - " + session.to + " on " + session.thread.title;
			}
		}
		select.appendChild(opt);
	}
}

function display_date(date) {
	return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + 
		date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}

function display_date_result(date) {
	var m = date.getMonth() + 1;
	var d = date.getDate();
	return date.getFullYear() + "年" + (m > 9 ? m : '0' + m) + "月" + 
		(d > 9 ? d : '0' + d) + "日";
}

function calc_max_width(ary) {
	var max = 0;
	for (var i in ary) {
		var r = ary[i];
		var w = get_text_width(r.id);
		if (w > max) {
			max = w;
		}
	}
	max += 4;
	return max;	
}

function display_result(session) {
	var div = document.getElementById("result");
	div.innerText = "";
	session.results.sort(sort_ups);
	var max = calc_max_width(session.results);
	div.innerHTML = display_date_result(new Date(session.from)) + ' （24小时）&nbsp;&nbsp;&nbsp;&nbsp;'
		+ '色中色聊天打屁第一高楼(SIS家族亲卫军分部) 发贴统计<br/>';
	div.innerHTML += '<br/>';
	div.innerHTML += '（按多少依次顺序）<br/>';
	div.innerHTML += '（低于10贴的不统计）<br/><br/>';

	for (var i in session.results) {
		var r = session.results[i];
		if (r.count < 11) break;
		div.innerHTML += 'ID: ' + pad(r.id, max) + '   发贴: ' + r.count + '   最后楼层: ' + r.last_floor + "<br/>";
	}
	var post = document.getElementById("btn_post");
	if (session.posted) {
		post.disabled = true;
	} else {
		post.disabled = false;
	}
}

function display_session(session) {
	document.getElementById("title").innerText = session.thread.title;
	if (session.thread.url == '') {
		if (session.pending.length > 0)
		document.getElementById("url").value = session.pending[0];
	} else
	document.getElementById("url").value = session.thread.url;
	if (session.type == "time") {
		var d = new Date(session.from);
		document.getElementById("from_time").value = display_date(d);
		d = new Date(session.to);
		document.getElementById("to_time").value = display_date(d);
		document.getElementById("from_floor").value = "";
		document.getElementById("to_floor").value = "";
	} else if (session.type == "floor") {
		document.getElementById("from_floor").value = session.from;
		document.getElementById("to_floor").value = session.to;
		document.getElementById("from_time").value = "";
		document.getElementById("to_time").value = "";
	} else {
		document.getElementById("from_floor").value = "";
		document.getElementById("to_floor").value = "";
		document.getElementById("from_time").value = "";
		document.getElementById("to_time").value = "";
	}
	display_result(session);
	clear_log();
	for (var i in session.pending) {
		log('Pending: ' + session.pending[i]);
	}
	log('Current URL: ' + session.current_url);
}

function get_selected_session() {
	var sel = document.getElementById("sessions");
	var opt = sel.options[sel.selectedIndex];
	if (opt.id != '-1') {
		for (var i in sessions) {
			if (sessions[i].id == opt.id) {
				return sessions[i];
			}
		}
	}
	return null;
}

function session_change() {
	var session = get_selected_session();
	if (session == null) {
		prepare_new_session();
	} else {
		display_session(session);
	}
}

function time_change() {
	document.getElementById("from_floor").value = "";
	document.getElementById("to_floor").value = "";
}

function floor_change() {
	document.getElementById("from_time").value = "";
	document.getElementById("to_time").value = "";
}

function prepare_new_session() {
	session = null;
	document.getElementById('title').innerText = '';
	document.getElementById('url').value = '';
	var d = new Date();
	d.setDate(d.getDate() - 1);
	d.setHours(0, 0, 0, 0);
	document.getElementById('from_time').value = display_date(d);
	d.setDate(d.getDate() + 1);
	document.getElementById('to_time').value = display_date(d);
}

function delete_session() {
	var session = get_selected_session();
	if (session == null) return;
	dao.deleteSession(session);
	var sel = document.getElementById('sessions');
	sel.removeChild(sel.options[sel.selectedIndex]);
	prepare_new_session();
}

function reset_session() {
	var session = get_selected_session();
	if (session == null) return;
	session.results = new Array();
	session.pending = new Array();
	session.thread.pages = new Array();
	if (session.thread.url != '')
	session.pending.push(session.thread.url);
	display_session(session);
}

function load_post_url() {
	var post_url = dao.loadPostUrl();
	if (post_url != undefined) 
		document.getElementById("post_url").value = post_url;
}

function post_session() {
	var url_prefix = dao.getUrlPrefix();
	if (url_prefix == null || url_prefix == "") {
		alert("Please specify URL Prefix in options");
		return;
	}
	var post_url = dao.loadPostUrl();
	if (post_url == "") {
		alert("Please specify post url in options");
		return;
	}

	var session = get_selected_session();
	if (session == null) {
		alert("Please select a session");
	}
	var html = document.getElementById('result').innerText;
	post_content(append_prefix(post_url), html);
	session.posted = true;
	dao.saveSession(session);
}

function init_statistics() {
	result_div = document.getElementById('result');
  	document.getElementById('btn_start').onclick = run_stat;
  	document.getElementById('btn_reset').onclick = reset_session;
  	document.getElementById('btn_delete').onclick = delete_session;
	document.getElementById('btn_post').onclick = post_session;

	document.getElementById('from_time').onchange = time_change;
	document.getElementById('to_time').onchange = time_change;
	document.getElementById('from_floor').onchange = floor_change;
	document.getElementById('to_floor').onchange = floor_change;	

	document.getElementById('sessions').onchange = session_change;
	
//	document.getElementById('post_ifm').src = chrome.extension.getURL('post_form.html');
	prepare_new_session();

	load_sessions();

	load_post_url();
}

	
